package com.Policing.menu;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.Policing.Fragment.Abnormal;
import com.Policing.Fragment.Query;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.Since_case.Since_case;
import com.bigkoo.alertview.OnDismissListener;
import com.Policing.Fragment.Fragment1;
import com.Policing.Fragment.Fragment2;
import com.Policing.Fragment.Fragment3;
import com.Policing.Fragment.Fragment4;
import com.Policing.Fragment.Fragment6;
import com.Policing.Fragment.Fragment7;
import com.Policing.Fragment.Maintain;
import com.Policing.Fragment.Maintenance_service;
import com.Policing.Fragment.Polling;
import com.Policing.Fragment.Repairs;
import com.Policing.Fragment.Scrap;
import com.Policing.R;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;
import com.tencent.android.tpush.XGPushManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SlideSideMenuExampleActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, OnDismissListener {
    // 列表数据
    private LinearLayout home, polling_da;
    private ArrayList<Group> gData = null;
    private ArrayList<ArrayList<Item>> iData = null;
    private ArrayList<Item> lData = null;
    private Context mContext;
    private ExpandableListView exlist_lol;
    private String user = "";
    private MyBaseExpandableListAdapter myAdapter = null;
    // 适配器
    private String getVersionUrl = "http://" + Ip_Set.IP + "/api/getVersionPDA";
    private String getAPK = "http://" + Ip_Set.IP + "/api/getAPKPDA";
    private SlideSideMenuTransitionLayout mSlideSideMenu;
    private long mExitTime;
    private FragmentManager fragmentManager;
    private Fragment fragment1, fragment2, fragment3, fragment4, fragment6, fragment7, Scrap, Repairs, Polling, Maintain, Maintenance_service, Abnomal, Query;
    private List<String> listString = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_slide_side_menu_example);
        mContext = this;
        listString = Since_case.set().getListString();
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        in();
        updateVersion();
        /*
        Fragment1-首页
        Fragment2-入库
        Fragment3-领用
        Fragment4-盘点
        Fragment5-租赁
        Fragment6-归还
        Fragment7-转移
        Allot-调拨
        Maintain-设备管理
        Polling-巡检
        Repairs-报修
        Scrap-报废
        */
    }

    private void in() {

        home = (LinearLayout) findViewById(R.id.home);
        //初始化碎片布局
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();
        fragment4 = new Fragment4();
        fragment6 = new Fragment6();
        fragment7 = new Fragment7();
        Abnomal = new Abnormal();
        Scrap = new Scrap();
        Repairs = new Repairs();
        Query = new Query();
        Polling = new Polling();
        Maintenance_service = new Maintenance_service();
        Maintain = new Maintain();

        mSlideSideMenu = (SlideSideMenuTransitionLayout) findViewById(R.id.slide_side_menu);
        fragmentManager = getSupportFragmentManager();

        fragmentManager.beginTransaction()
                .replace(R.id.id_framelayout2, fragment1).commit();
        home.setOnClickListener(v -> {
            fragmentManager.beginTransaction()
                    .replace(R.id.id_framelayout2, fragment1).commit();
            mSlideSideMenu.toggle();
        });
        exlist_lol = (ExpandableListView) findViewById(R.id.expendlist);
        exlist_lol.setGroupIndicator(null);//数据准备
        gData = new ArrayList<Group>();
        iData = new ArrayList<ArrayList<Item>>();
        gData.add(new Group("资产管理", R.mipmap.assets, listString.get(0)));
        gData.add(new Group("设备管理", R.mipmap.supervisory, listString.get(1)));
        gData.add(new Group("巡检管理", R.mipmap.xunjian, listString.get(2)));
        //固定资产组
        lData = new ArrayList<Item>();
        lData.add(new Item(R.mipmap.in_storage, "入库", listString.get(3)));
        lData.add(new Item(R.mipmap.receive, "领用", listString.get(4)));
        lData.add(new Item(R.mipmap.check, "盘点", listString.get(5)));
        lData.add(new Item(R.mipmap.huan, "归还", listString.get(6)));
        lData.add(new Item(R.mipmap.transfer, "调拨", listString.get(7)));
        lData.add(new Item(R.mipmap.scrap, "报废", listString.get(8)));
        lData.add(new Item(R.mipmap.repairs, "报修", listString.get(9)));
        iData.add(lData);
        lData = new ArrayList<Item>();
        lData.add(new Item(R.mipmap.maintain_icon, "保养", listString.get(10)));
        lData.add(new Item(R.mipmap.maintain, "维修", listString.get(11)));
        lData.add(new Item(R.mipmap.query, "查询", listString.get(12)));
        iData.add(lData);
        lData = new ArrayList<Item>();
        lData.add(new Item(R.mipmap.tasks, "巡检任务", listString.get(13)));
        lData.add(new Item(R.mipmap.errors, "异常处理", listString.get(14)));
        iData.add(lData);
        myAdapter = new MyBaseExpandableListAdapter(gData, iData, this);
        exlist_lol.setAdapter(myAdapter);
        exlist_lol.setOnGroupClickListener((parent, v, groupPosition, id) -> false);
        //为列表设置点击事件
        exlist_lol.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
            if (groupPosition == 0) {
                switch (childPosition) {
                    case 0:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, fragment2).commit();
                        break;
                    case 1:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, fragment3).commit();
                        break;
                    case 2:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, fragment4).commit();
                        break;
                    case 3:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, fragment6).commit();
                        break;
                    case 4:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, fragment7).commit();
                        break;

                    case 5:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, Scrap).commit();
                        break;
                    case 6:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, Repairs).commit();
                        break;
                }
                mSlideSideMenu.toggle();
            }
            if (groupPosition == 1) {
                switch (childPosition) {
                    case 0:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, Maintain).commit();
                        break;
                    case 1:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, Maintenance_service).commit();
                        break;
                    case 2:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, Query).commit();
                        break;
                }
                mSlideSideMenu.toggle();
            }
            if (groupPosition == 2) {
                switch (childPosition) {
                    case 0:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, Polling).commit();
                        break;
                    case 1:
                        fragmentManager.beginTransaction()
                                .replace(R.id.id_framelayout2, Abnomal).commit();
                        break;
                }
                mSlideSideMenu.toggle();
            }
            return true;
        });
    }

    @Override
    public void onBackPressed() {
        if (mSlideSideMenu != null && mSlideSideMenu.closeSideMenu()) {
            // Closed the side menu, override the default back pressed behavior
            return;
        }

        super.onBackPressed();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // TODO Auto-generated method stub
        switch (position) {
            case 0:
                fragmentManager.beginTransaction()
                        .replace(R.id.id_framelayout2, fragment1).commit();
                break;
            case 1:
                fragmentManager.beginTransaction()
                        .replace(R.id.id_framelayout2, fragment2).commit();
                break;
            case 2:
                fragmentManager.beginTransaction()
                        .replace(R.id.id_framelayout2, fragment3).commit();
                break;
            case 3:
                fragmentManager.beginTransaction()
                        .replace(R.id.id_framelayout2, fragment4).commit();
                break;
            case 4:
                fragmentManager.beginTransaction()
                        .replace(R.id.id_framelayout2, fragment6).commit();
                break;
            case 5:
                fragmentManager.beginTransaction()
                        .replace(R.id.id_framelayout2, fragment7).commit();
                break;
            case 6:
                fragmentManager.beginTransaction()
                        .replace(R.id.id_framelayout2, Scrap).commit();
                break;
            case 7:
                fragmentManager.beginTransaction()
                        .replace(R.id.id_framelayout2, Repairs).commit();
                break;
        }
        mSlideSideMenu.toggle();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                XGPushManager.unregisterPush(this);
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void opmenu() {
        mSlideSideMenu.toggle();
    }

    @Override
    public void onDismiss(Object o) {

    }

    /**
     * 检查更新版本
     */
    private void updateVersion() {
        // 获取当前版本号信息
        PackageInfo packInfo = null;
        try {
            packInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        assert packInfo != null;
        final int versionCode = packInfo.versionCode;
        //获取服务器里apk版本号
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody body = new FormBody.Builder()/*.add("source",Since_case.set().getSource())*/.build();
        Request request = new Request.Builder().url(getVersionUrl).post(body).build();
        Log.e("测试数据", getVersionUrl);
        try {
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    runOnUiThread(() -> Toast.makeText(SlideSideMenuExampleActivity.this, "请检查网络", Toast.LENGTH_SHORT).show());

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        assert response.body() != null;
                        InputStream inputStream = response.body().byteStream();
                        //使用IO流读取数据
                        String line = null;
                        StringBuffer sb = new StringBuffer();
                        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                        while ((line = in.readLine()) != null) {
                            sb.append(line);
                        }
                        inputStream.close();
                        in.close();
                        String versionInfo = sb.toString();
                        final int updateVersion = Integer.parseInt(versionInfo.substring(versionInfo.indexOf(":") + 1));
                        Log.i("测试1", "version: " + versionCode + "--updateVersion:" + updateVersion);
                        //是否弹出有高版本时可以更新的提示框
                        if (versionCode < updateVersion) {
                            runOnUiThread(() -> {
                                final AlertDialog builder = new AlertDialog.Builder(SlideSideMenuExampleActivity.this)
                                        .setTitle("更新提示")
                                        .setMessage("有新版本是否更新！")
                                        .setNegativeButton("否", (dialog, which) -> dialog.dismiss())
                                        .setPositiveButton("是", (dialog, which) -> {
                                            downloadAPK();
                                            dialog.dismiss();
                                        }).create();
                                builder.setCanceledOnTouchOutside(false);
                                builder.show();
                            });
                        }
                    } else {
                        Log.i("测试", "请求错误 ");
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            Log.i("测试", "请求错误 ");
        }

    }

    /**
     * 下载最新版apk
     */
    private void downloadAPK() {
        //弹出进度提示框
        showDialog(SlideSideMenuExampleActivity.this);
        OkHttpClient okHttpClient = new OkHttpClient();
        final FormBody body = new FormBody.Builder().build();
        final Request request = new Request.Builder().url(getAPK).post(body).addHeader("Accept-Encoding", "identity").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(SlideSideMenuExampleActivity.this, "请检查网络！", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    assert response.body() != null;
                    final InputStream in = response.body().byteStream();
                    //保存SD卡
                    final File path = new File(Environment.getExternalStorageDirectory(), "Xt_slab_apk_pda");
                    Log.e("测试", String.valueOf(path));
                    if (!path.exists()) {//判断路径文件夹是否存在
                        path.mkdirs();//创建文件夹
                    }
                    final File file = new File(path, "app.apk");
                    if (file.exists()) {//判断路径文件是否存在
                        file.delete();//删除文件
                    }
                    if (!file.exists()) {
                        file.createNewFile();//创建文件
                        FileOutputStream output = null;
                        try {
                            output = new FileOutputStream(file);
                            int len = 0;
                            byte[] buffer = new byte[1024];
                            while ((len = in.read(buffer)) != -1) {
                                output.write(buffer, 0, len);
                                Log.i("测试", "len: " + len);
                            }
                            output.flush();
                        } catch (IOException e) {
                            Log.i("测试", "IOException: ");
                        }
                        assert output != null;
                        output.close();
                    }

                    runOnUiThread(() -> {
                        progressDialog.cancel();
                        // 安装apk
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        Uri data;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
                            // 通过FileProvider创建一个content类型的Uri
                            data = FileProvider.getUriForFile(SlideSideMenuExampleActivity.this, "com.Assetspolling.provider", file);
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
                        } else {
                            data = Uri.fromFile(file);
                        }
                        intent.setDataAndType(data, "application/vnd.android.package-archive");
                        startActivity(intent);
                    });

                } else {
                    Log.i("测试", "服务器异常！");
                }
            }
        });
    }

    private ProgressDialog progressDialog;

    private void showDialog(final Context context) {
        runOnUiThread(() -> {
            progressDialog = new ProgressDialog(context);
            progressDialog.setTitle("正在下载中");
            progressDialog.setMessage("Loading...");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        });
    }
}
